<?php


/**
 * This file is part from Ewuroweb Shop
 *
 * @package 
 * @author Ivan I. Atanasov <i.atanasov@viscomp.bg>
 */

class BaseController extends Zend_Controller_Action {

    function init() {
        /*
         * Init a Breadcrumb
         */
        $uri = $this->_request->getPathInfo();
        $activeNav = $this->view->navigation()->findByUri($uri);
        $activeNav->active = TRUE;
    }

    //=============================================================================================
    
    function dispatch($action) {
        // Get all request parameters
        $params = $this->_getAllParams();
        
        // Get all action method parameters
        $method_params_array = $this->_getActionParams($action);
        
        $data = array(); // It will sent to the action
        

        foreach($method_params_array as $param) {
            $name = $param->getName();
            if($param->isOptional()) { // Check whether the parameter is optional
                // If there is no data to send, use the default
                $data[$name] = ! empty($params[$name]) ? $params[$name] : $param->getDefaultValue();
            }
            elseif(empty($params[$name])) {
                // The parameter cannot be empty as defined
                throw new Exception('Parameter: ' . $name . ' Cannot be empty');
            }
            else {
                $data[$name] = $params[$name];
            }
        }
         
        // Notify helpers of action preDispatch state
        $this->_helper->notifyPreDispatch();
        $this->preDispatch();
        
        // Invoke the action and pass the request parameters as actions method parameters, according to their order and names.
        call_user_func_array(array($this, $action), $data);
        
        $this->postDispatch();
        $this->_helper->notifyPostDispatch();
    }
    //=============================================================================================
    
    private function _getActionParams($action) {
        $classRef = new ReflectionObject($this);
        $className = $classRef->getName();
        $funcRef = new ReflectionMethod($className, $action);
        $paramsRef = $funcRef->getParameters();
        
        return $paramsRef;
    }
    //=============================================================================================

}
